<template>
  <el-card>
    <!-- 1.0 标题 -->
    <template #header>账号添加</template>
    <!-- 2.0 内容 -->
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="账号" prop="user">
        <el-input
          type="text"
          v-model="ruleForm.user"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="region">
        <el-select v-model="ruleForm.region" placeholder="请选择管理员">
          <el-option label="超级管理员" value="超级管理员"></el-option>
          <el-option label="普通管理员" value="普通管理员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { validateUser, validatePass } from '@/utils/validate.js'
import { addUsers } from '@/api/users.js'
export default {
  data() {
    return {
      ruleForm: {
        pass: '',
        user: '',
        region: ''
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'blur' }],
        user: [{ validator: validateUser, trigger: 'blur' }],
        region: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { code, msg } = await addUsers({
            account: this.ruleForm.user,
            password: this.ruleForm.pass,
            userGroup: this.ruleForm.region
          })
          if (code === 0) {
            this.$router.push('/num/list')
          }
        } else {
          this.$message({
            message: '添加失败',
            type: 'error'
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 178px;
}
</style>
